<template>
  <div class="uplode">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-imgError="imgerror" :src="value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDLadU7h7KL9kCUYN0PchX8TZQ2OVNzNYa',
  SecretKey: 'rTt53nHXnqeEZgZEfssfFbjeLn11oNhm'
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imgerror: require('@/assets/mmm.jpg')
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.$emit('input', res.data.url)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest (res) {
      // console.log('res', res)
      // 初始化
      this.loading = true
      this.percentage = 0
      cos.putObject(
        {
          Bucket: 'womizui-1308950821' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = progressData.percent * 100
            if (progressData.percent === 1) {
              this.loading = false
            }
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          // console.log('data', data)
          this.$emit('input', 'http://' + data.Location)
          // this.imageUrl = 'http://' + data.Location
        }
      )
    }
  }
}
</script>

<style scoped lang="scss">
.uplode {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
